package data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 *
 * @author Matthew Poulos
 * This class handles the database communication
 * 
 */
public class DatabaseHandler  {
	private final static DatabaseHandler INSTANCE = new DatabaseHandler();

    /**
     * @return The instance of the Database Handler
     */
   public static DatabaseHandler getInstance() {
       return DatabaseHandler.INSTANCE;
   }

    private Connection conn;

    private DatabaseHandler() {
        this("jdbc:mysql://localhost/sensor_data", "root", "");
    }

    private DatabaseHandler(String url, String user, String password) {
        try {
            Class.forName ("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection(url, user, password);
            if(conn != null) {
                System.out.println("Database Connection established");
            } else {
                System.out.println("Database Connection failed");
            }

        } catch(SQLException e) {
            System.out.println("Connection FAILED to database");
            e.printStackTrace();
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This method handles insertion of sensor data into the database
     * @param sensorID the sensor ID, a combination of spotID and sensor index
     * @param time The time of the reading
     * @param value The value gathered by the sensor
     */

    public  void insert(byte sensorID, long time, int value) {
        try {
            PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Data VALUES(?,?,?)");
            pstmt.setByte(1, sensorID);
            pstmt.setLong(2, time);
            pstmt.setFloat(3, value/(float)(0x10000));
            pstmt.executeUpdate();
            pstmt.close();
        } catch(SQLException e) {
            System.out.println("Insert error");
            e.printStackTrace();
        }
    }
}
